package com.onenine.app.adapter;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.onenine.app.R;
import com.onenine.app.activity.BrowserImageActivity;
import com.onenine.app.model.PostItem;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.MultiImageRandom;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.RoundViewOutlineProvider;
import com.onenine.app.view.SpcCountBar;
import com.onenine.app.view.nineimage.NineGridImageView;
import com.onenine.chat.util.SimpleCommonUtils;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.ScreenUtils;

import java.util.ArrayList;
import java.util.Arrays;

import cn.jzvd.JZCacheProxy;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

/**
 * 推荐帖子
 */
public class CRecAdapter extends BaseMultiItemQuickAdapter<PostItem, BaseViewHolder> {

    private int mVideoWidth, mMaxWidth;
    private int mAvatarSize, mDescPadding;
    private MultiImageAdapter.OnItemImageClickListener mOnMultiImageItemClickListener;

    public CRecAdapter(MultiImageAdapter.OnItemImageClickListener listener) {
        super(new ArrayList<>());
        mOnMultiImageItemClickListener = listener;
        Resources resource = ApUtils.getApp().getResources();
        mVideoWidth = resource.getDimensionPixelOffset(R.dimen.small_video_width);
        mAvatarSize = resource.getDimensionPixelSize(R.dimen.avatar_size_52dp);
        mDescPadding = resource.getDimensionPixelOffset(R.dimen.dp10);
        mMaxWidth = ScreenUtils.getScreenWidth()
                - 2 * resource.getDimensionPixelOffset(R.dimen.dp25);
        addItemType(DataType.POST_IMAGE_TYPE, R.layout.layout_post_image_item);
        addItemType(DataType.POST_VIDEO_TYPE, R.layout.layout_post_video_item);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void convert(BaseViewHolder holder, PostItem item) {
        handleCommonInfo(holder, item);
        switch (holder.getItemViewType()) {
            case DataType.POST_IMAGE_TYPE:
                handleImagesInfo(holder, item);
                break;
            case DataType.POST_VIDEO_TYPE:
                handleVideoInfo(holder, item);
                break;
        }
    }

    /**
     * 处理通用数据
     *
     * @param holder
     * @param item
     */
    private void handleCommonInfo(BaseViewHolder holder, PostItem item) {
        TextView tvName = holder.getView(R.id.tv_name);
        tvName.setText(item.getNickName());
        ImageView ivAvatar = holder.getView(R.id.aiv_avatar);
        GlideUtils.loadSrcImage(ApUtils.getApp(), ivAvatar, CHelper.getOssThumbImageUrl(item.getPhoto(), mAvatarSize));
        holder.setImageResource(R.id.iv_sex, RoleResLoader.getRoleDrawableResourceId(RoleResLoader
                .DynamicResName.COMMUNITY_SEX_ICON, item.getSex()));
        holder.setText(R.id.tv_date, item.getDate());
        View svBg = holder.getView(R.id.ll_content);
        TextView tvDesc = holder.getView(R.id.tv_desc);
        if ("".equals(item.getPostDesc())) {
            tvDesc.setVisibility(View.GONE);
        } else {
            tvDesc.setVisibility(View.VISIBLE);
            SimpleCommonUtils.spannableEmoticonFilter(tvDesc, item.getPostDesc());
        }
        if ("".equals(item.getPostPvUrl())) {
            tvDesc.setPadding(0, 0, 0, 0);
        } else {
            tvDesc.setPadding(0, 0, 0, mDescPadding);
        }
        svBg.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.POST_ITEM_BG, item.getSex()));
    }

    /**
     * 处理图片数据
     *
     * @param holder
     * @param item
     */
    private void handleImagesInfo(BaseViewHolder holder, PostItem item) {
        final String[] imageUrls = item.getPostPvUrl().split(",");
        final ImageView singleImageView = holder.getView(R.id.siv_image);
        final NineGridImageView multiImageView = holder.getView(R.id.miv_image);
        SpcCountBar sprBar = holder.getView(R.id.spr_bar);
        sprBar.setListShow(true);
        if (imageUrls.length == 1) {
            multiImageView.setVisibility(View.GONE);
            if (TextUtils.isEmpty(imageUrls[0])) {
                //无图
                sprBar.setData(item, item.getPostPkId(), DataType.POST_TOPIC, 0, item.getPostDesc(), null);
                singleImageView.setVisibility(View.GONE);
            } else {
                //加载自适应单图
                sprBar.setData(item, item.getPostPkId(), DataType.POST_TOPIC, 0, item.getPostDesc(), imageUrls[0]);
                singleImageView.setVisibility(View.VISIBLE);
                GlideUtils.loadSquareImageFitWidth(mContext, singleImageView, imageUrls[0], mMaxWidth);
                singleImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BrowserImageActivity.launchActivity((Activity) mContext, singleImageView, imageUrls[0]);
                    }
                });
            }
        } else {
            //加载不规则多图
            singleImageView.setVisibility(View.GONE);
            multiImageView.setVisibility(View.VISIBLE);
            multiImageView.setAdapter(new MultiImageAdapter(multiImageView, mOnMultiImageItemClickListener));
            int spanType = getMultiSpanType(item, imageUrls.length);
            multiImageView.setImagesData(new ArrayList(Arrays.asList(imageUrls)), spanType);
            sprBar.setData(item, item.getPostPkId(), DataType.POST_TOPIC, spanType, item.getPostDesc(), imageUrls[0]);
        }
    }

    /**
     * 处理视频数据
     *
     * @param holder
     * @param item
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void handleVideoInfo(BaseViewHolder holder, PostItem item) {
        SpcCountBar sprBar = holder.getView(R.id.spr_bar);
        sprBar.setListShow(true);
        String[] videos = item.getPostPvUrl().split(",");
        JzvdStd jzTextureView = holder.getView(R.id.jz_video_view);
        jzTextureView.setOutlineProvider(new RoundViewOutlineProvider(ApUtils.getApp().getResources()
                .getDimensionPixelOffset(R.dimen.common_round_corner)));
        jzTextureView.setClipToOutline(true);
        if (videos.length == 2) {
            //有封面
            sprBar.setData(item, item.getPostPkId(), DataType.POST_TOPIC, 0
                    , item.getPostDesc(), CHelper.getOssThumbImageUrl(videos[0], mVideoWidth));
            jzTextureView.setUp(JZCacheProxy.getJzCacheProxy(ApUtils.getApp())
                    .getCacheDataSource(videos[1]), Jzvd.SCREEN_WINDOW_LIST);
            GlideUtils.loadVideoImageFitWidth(mContext, jzTextureView.thumbImageView, videos[0]
                    , mMaxWidth, new GlideUtils.OnFitCallback() {
                        @Override
                        public void callback(Pair<Float, Float> sizePair) {
                            if (sizePair == null) {
                                return;
                            }
                            ViewGroup.LayoutParams lp = jzTextureView.getLayoutParams();
                            lp.width = sizePair.first.intValue();
                            lp.height = sizePair.second.intValue();
                        }
                    });
        } else if (videos.length == 1) {
            //无封面
            sprBar.setData(item, item.getPostPkId(), DataType.POST_TOPIC, 0
                    , item.getPostDesc(), null);
            jzTextureView.setUp(JZCacheProxy.getJzCacheProxy(ApUtils.getApp())
                    .getCacheDataSource(videos[0]), Jzvd.SCREEN_WINDOW_LIST);
        }
    }

    /**
     * 复用随机得到的SpanType
     *
     * @param postItem
     * @return
     */
    private int getMultiSpanType(PostItem postItem, int imageCount) {
        int spanType;
        if (postItem.getSpanType() == -1) {
            spanType = MultiImageRandom.getRandomSpanType(imageCount);
            postItem.setSpanType(spanType);
        } else {
            spanType = postItem.getSpanType();
        }
        return spanType;
    }

}
